import React, { Component } from 'react';
import { StyleSheet, View, Text, Alert, TouchableOpacity, PixelRatio, Image} from 'react-native';
import { Container, Content, Form, Item, Picker, Icon, Textarea, Button } from 'native-base';
import ImagePicker from 'react-native-image-picker';
import ImageShow from '../components/comm/ImageShow';

export default class FloatingLabelExample extends Component {
    constructor(props) {
        super(props);
        this.state = {
            macid: "",
            content: "",
            machinaList: [],
            imgSoure:[],
            modalVisible:false,
            imgPath:""
        };
    }
    componentDidMount() {
        url = global.urltype + global.urlpath + ":" + global.urlport + "/api/Machine/machine";
        para = 'pageIndex=1&pageSize=100';
        url += '?' + para;
        return fetch(url)
            .then(response => response.json())
            .then(json => {
                if (json.recode == 1) {
                    this.setState({ machinaList: json.data });
                }
            })
            .catch(error => {
                console.error(error);
            });
    }
    handleChangeMacID = (macid) => {
        this.setState({ macid })
    }
    handleChangeContent = (content) => {
        this.setState({ content })
    }
    goback = () => {
        const { navigate, goBack, state } = this.props.navigation;
        state.params.callback();
        this.props.navigation.goBack();
    }
    handleSubmit=()=>{
        if(this.state.macid == "" || this.state.content==""){
            Alert.alert("错误提示", "请选择设备并填写描述", [{ text: '关闭' }])
            return;
        }
        //参数
        let formData = new FormData();
        formData.append("Macid", this.state.macid);  
        formData.append("MtncContent", this.state.content);  
        imgAry = this.state.imgSoure;
        for (var i = 0; i < imgAry.length; i++){
            let file = { uri: imgAry[i]['uri'], type: 'multipart/form-data', name: imgAry[i]['fileName'] };
            formData.append("files", file); 
        }
        url = global.urltype + global.urlpath + ":" + global.urlport + "/api/MachineWX/Add";
        return fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': global.token
            },
            body: formData
        })
            // .then(response => response.json())
            .then(() => {
                Alert.alert("提交成功", "提交成功", [
                    {
                        text: '确认',
                        onPress: () => {
                            this.goback();
                        }
                    }
                ]);
            })
            .catch(error => {
                console.error(error);
            });

    }
    selectPhotoTapped=()=> {
        const options = {
            title: '请选择',
            cancelButtonTitle: '取消',
            takePhotoButtonTitle: '拍照',
            chooseFromLibraryButtonTitle: '选择相册',
            quality: 1.0,
            maxWidth: 500,
            maxHeight: 500,
            storageOptions: {
                skipBackup: true
            }
        };

        ImagePicker.showImagePicker(options, (response) => {
            console.log('Response = ', response);

            if (response.didCancel) {
                console.log('User cancelled photo picker');
            }
            else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            }
            else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
            }
            else {
                imgPath = this.state.imgPath;
                if (imgPath==""){
                    imgPath = response.uri;
                }else{
                    imgPath = "^"+response.uri;
                }
                this.setState({
                    imgSoure: this.state.imgSoure.concat(response),
                    imgPath: imgPath
                });
            }
        });
    }
    callbackScan = (macid)=>{
        this.setState({ macid});
    }
    handleDelImg = (idx)=>{
        Alert.alert("图片删除","确认删除图片吗？",[
            { text: '取消'},
            { text: '删除', onPress: () => {
                imgSoure = this.state.imgSoure;
                imgSoure.splice(idx, 1);
                this.setState(imgSoure);
            }},
        ])
    }
    handleToggleModalVisible = () => {
        alert(this.state.imgPath)
        this.setState({
            modalVisible: !this.state.modalVisible
        })
    }
    render() {
        return (
            <Container>
                <Content>
                    <Form>
                        <Item picker>
                            <Picker
                                mode="dropdown"
                                iosIcon={<Icon name="ios-arrow-down-outline" />}
                                style={{ width: undefined }}
                                placeholder="Select your SIM"
                                placeholderStyle={{ color: "#bfc6ea" }}
                                placeholderIconColor="#007aff"
                                selectedValue={this.state.macid}
                                onValueChange={this.handleChangeMacID}
                            >
                                <Picker.Item label="---" value="" />
                                {this.state.machinaList.map((itemObj, idx) => {
                                    return (
                                        <Picker.Item key={idx} label={itemObj.macName + ":" + itemObj.modelNo} value={itemObj.macID} />
                                    )
                                }
                                )}
                            </Picker>
                            {/* <Icon name='md-qr-scanner' style={{ fontSize:30}}
                                onPress={this.props.navigation.navigate('Scan',
                                    {
                                        callback: (macid) => {
                                            this.callbackScan(macid)
                                        }
                                    })
                                }
                            /> */}
                        </Item>
                        <Textarea rowSpan={5} bordered placeholder="问题描述" value={this.state.content} onChangeText={this.handleChangeContent} />
                        <View style={addStyle.ImgContainer}>
                            {
                                this.state.imgSoure.map((item,idx)=>{
                                    return (
                                        <TouchableOpacity 
                                            onLongPress={() => { this.handleDelImg(idx)}}
                                            // onPress={this.handleToggleModalVisible}
                                        >
                                            <View style={[addStyle.Img, addStyle.ImgContainer, { margin: 10 }]}>
                                                <Image style={addStyle.Img} source={item} />
                                            </View>
                                        </TouchableOpacity>
                                    )
                                })
                            }
                            {
                                this.state.imgSoure.length < 6 ? 
                                <TouchableOpacity onPress={this.selectPhotoTapped}>
                                    <View style={[addStyle.Img, addStyle.ImgContainer, { margin: 10 }]}>
                                        <Text style={{textAlign:"center",flex:1}}>选择图片</Text>
                                    </View>
                                </TouchableOpacity>:
                                <Text/>
                            }
                        </View>
                    </Form>
                    <View style={addStyle.ButtonView}>
                        <Button default block onPress={this.handleSubmit}>
                            <Text style={addStyle.ButtonText}> 提交 </Text>
                        </Button>
                    </View>
                    <ImageShow
                        modalVisible={this.state.modalVisible}
                        toggleModalVisible={this.handleToggleModalVisible}
                        imgPath={this.state.imgPath}
                        imgtype = "local"
                    />
                </Content>
            </Container>
        );
    }
}

const addStyle = StyleSheet.create({
    ButtonView: {
        paddingHorizontal: 10,
        paddingVertical: 20,
    },
    ButtonText: {
        color: "#fff",
    },
    ImgContainer: {
        borderColor: '#9B9B9B',
        borderWidth: 1 / PixelRatio.get(),
        alignItems: 'center',
        flexDirection:"row",
        flexWrap:"wrap"
    },
    Img: {
        width: 66,
        height: 66
    }
});